<?php

class AdminModel extends MCActiveRecord
{
	protected $_table = 'admins';
	protected $_id = 'admin_id';
	
	public function relations()
	{
		return array(
			'role' => array(self::BELONGS_TO, 'RoleModel', 'role_id')
		);
	}
	
	/**
	 * 设置登录状态
	 * @param <class>CUserIdentity $identity
	 * @param array $user
	 */
	public function login($identity, $user)
	{
		Yii::app()->user->login($identity);
		Yii::app()->user->setState('admin_id', $user->admin_id);
		Yii::app()->user->setState('admin_name', $user->admin_name);
		Yii::app()->user->setState('role_id', $user->role_id);
		Yii::app()->user->setState('role_name', $user->role->role_name);
		if ($user->role->act_rights != '*')
		{
			$act_rights = json_decode($user->role->act_rights, true);
			//所有管理员都可以使用ajax下的方法
			$act_rights['ajax'] = '*';
			$act_rights['admin'][] = 'mypass';
		}
		else
		{
			$act_rights = $user->role->act_rights;
		}
		
		/*
		//测试权限
		Yii::app()->user->setState('act_rights', array(
			'index' => array('index', 'setting'),
			'role' => array('index', 'add', 'edit', 'delete'),
			'master' => array(
				'index' => array('index', 'login'),
				'role' => array('add')
			)
		));
		*/
		Yii::app()->user->setState('act_rights', $act_rights);
	}
	
	/**
	 * 保存管理员
	 * @param string $admin_name
	 * @param string $admin_pass
	 * @param int $role_id
	 * @return boolean
	 */
	public function admin_save($admin_name, $admin_pass, $role_id)
	{
		$this->admin_name = $admin_name;
		$this->admin_pass = md5($admin_pass);
		$this->role_id = (int) $role_id;
		$this->add_time = time();
		return $this->save();
	}
	
	/**
	 * 修改管理员密码
	 * @param int $admin_id
	 * @param string $admin_pass
	 * @return boolean
	 */
	public function save_pass($admin_id, $admin_pass)
	{
		$this->admin_id = (int) $admin_id;
		$this->admin_pass = md5($admin_pass);
		$this->setIsNewRecord(false);
		return $this->save(true, array('admin_pass'));
	}
	
	/**
	 * 修改管理员权限
	 * @param int $admin_id
	 * @param int $role_id
	 * @return boolean
	 */
	public function save_role($admin_id, $role_id)
	{
		$this->admin_id = (int) $admin_id;
		$this->role_id = (int) $role_id;
		$this->setIsNewRecord(false);
		return $this->save(true, array('role_id'));
	}
	
	/**
	 * 修改管理员状态
	 * @param int $admin_id
	 * @param int $status
	 * @return boolean
	 */
	public function save_status($admin_id, $status)
	{
		$this->admin_id = (int) $admin_id;
		$this->status = (int) $status;
		if (!in_array($status, array('0', '1')))
		{
			return false;
		}
		$this->setIsNewRecord(false);
		return $this->save(true, array('status'));
	}
}